package com.ankang.controller;

import com.ankang.entity.ChannelLevel;
import com.ankang.util.RFIDUtil;
import com.ankang.util.UHFTcpReaderTool;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 基于UHFTcpReaderTool的RFID读卡器控制器
 */
public class RFIDReader {

    private static final Logger log = LoggerFactory.getLogger(RFIDReader.class);

    private static final int READ_COUNT = 20;
    private static final int READ_INTERVAL = 100;

    private final String rfidIp;
    private final int rfidPort;
    private final Lock lock = new ReentrantLock();
    private UHFTcpReaderTool uhfTcpReader;
    private boolean isConnected = false;

    public RFIDReader(ChannelLevel channelLevel) {
        this.rfidIp = channelLevel.getRfidIp();
        this.rfidPort = channelLevel.getRfidPort();
        Assert.hasText(rfidIp, "读卡器IP不能为空");
        Assert.isTrue(rfidPort >= 1024 && rfidPort <= 65535, "端口必须在1024-65535范围内");
    }

    public String readRfid1() {
//        RFIDUtil.(rfidIp, rfidPort);
        RFIDUtil rfidUtil = new RFIDUtil();
        String rfid = rfidUtil.getRfid(rfidIp, rfidPort);
        return rfid;
    }



    /**
     * 读取RFID标签（增加锁超时控制）
     */
    public String readRfid() {
        lock.lock();
        try {
            if (uhfTcpReader == null) {
                uhfTcpReader = new UHFTcpReaderTool(rfidIp, rfidPort);
            }

            // 修复：增加连接重试间隔，避免频繁重试导致锁竞争
            int connectRetry = 0;
            while (connectRetry < 3 && (!isConnected && !connect())) {
                connectRetry++;
                log.warn("读卡器({}:{})连接失败，第{}次重试", rfidIp, rfidPort, connectRetry);
                Thread.sleep(1000); // 延长重试间隔到1秒
            }

            if (!isConnected) {
                log.error("读卡器({}:{})多次连接失败，放弃本次读取", rfidIp, rfidPort);
                return null;
            }

            if (!uhfTcpReader.setWorkModeForTargetEpc()) {
                log.error("读卡器({}:{})设置工作模式失败", rfidIp, rfidPort);
                uhfTcpReader.disconnect();
                isConnected = false;
                return null;
            }

            String epc = uhfTcpReader.readTargetEpc(READ_COUNT, READ_INTERVAL);
            log.info("读卡器({}:{})读取结果: {}", rfidIp, rfidPort, epc);
            return epc;

        } catch (InterruptedException e) {
            log.error("读卡器({}:{})读取被中断", rfidIp, rfidPort, e);
            Thread.currentThread().interrupt();
            return null;
        } finally {
            if (uhfTcpReader != null) {
                uhfTcpReader.disconnect();
            }
            isConnected = false;
            lock.unlock();
        }
    }

    private boolean connect() {
        try {
            isConnected = uhfTcpReader.connect();
            return isConnected;
        } catch (Exception e) {
            log.error("读卡器连接异常", e);
            isConnected = false;
            return false;
        }
    }

    public void release() {
        if (uhfTcpReader != null) {
            uhfTcpReader.disconnect();
            isConnected = false;
        }
    }
}